import React from 'react';
import { Graph } from '@antv/x6';
import '@antv/x6-react-shape';

const Index = () => {
  const divRef = React.useRef<HTMLDivElement | null>(null);

  React.useEffect(() => {
    if (divRef.current !== null) {
      const graph = new Graph({
        container: divRef.current,
        grid: true,
      });

      graph.addEdge({
        source: [228.84550125020417, 100.76702664502545],
        target: [416.2834258874138, 72.03741369165368],
        vertices: [{ x: 300, y: 150 }],
        attrs: {
          line: {
            sourceMarker: {
              tagName: 'path',
              d: 'M 20 -10 0 0 20 10 Z',
            },
            targetMarker: {
              tagName: 'path',
              stroke: 'green',
              strokeWidth: 2,
              fill: 'yellow',
              d: 'M 20 -10 0 0 20 10 Z',
            },
          },
        },
      });

      const source = graph.addNode({
        x: 40,
        y: 40,
        width: 100,
        height: 40,
        shape: 'react-shape',
        ports: {
          items: [
            { group: 'in', id: 'in1' },
            { group: 'in', id: 'in2' },
            { group: 'out', id: 'out1' },
            { group: 'out', id: 'out2' },
          ],
          groups: {
            in: {
              position: { name: 'top' },
              attrs: {
                fo: {
                  width: 10,
                  height: 10,
                  x: -5,
                  y: -5,
                  magnet: 'true',
                },
              },
              zIndex: 1,
            },
            out: {
              position: { name: 'bottom' },
              attrs: {
                fo: {
                  width: 10,
                  height: 10,
                  x: -5,
                  y: -5,
                  magnet: 'true',
                },
              },
              zIndex: 1,
            },
          },
        },
        data: { text: 'hello' },
        component: (node: any) => {
          const data: any = node.getData();
          console.log('component', node, data);
          return <div style={{ background: 'blue', color: '#fff', textAlign: 'center', lineHeight: '40px' }}>{data.text}</div>;
        },
      });

      const target = graph.addNode({
        shape: 'react-shape',
        x: 140,
        y: 160,
        width: 100,
        height: 40,
        data: { text: 'world' },
        component: (node: any) => {
          const data: any = node.getData();
          console.log('component', node, data);
          return <div style={{ background: 'blue', color: '#fff', textAlign: 'center', lineHeight: '40px' }}>{data.text}</div>;
        },
      });

      graph.addEdge({
        source,
        target,
      });
    }
  });

  return (
    <>
      <div style={{ width: '100%', height: '100%' }} ref={divRef} />
    </>
  );
};

export default Index;

const NodeElement = () => {};
